<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoles">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" stripe style="width: 100%" border>
        <el-table-column align="center" type="expand" label="#">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <!-- 一级列表循环 -->
            <el-row
              v-for="(item1,index1) in scope.row.children"
              :key="item1.id"
              :class="['boderb',index1==0? 'boders':'','fcenter']"
            >
              <el-col :span="5">
                <el-tag
                  type="primary"
                  closable
                  @close="deleteTags(scope.row,item1.id)"
                >{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 二级列表循环 -->
                <el-row
                  v-for="(item2,index2) in item1.children"
                  :key="item2.id"
                  :class="[index2===0? '':'boders','fcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="deleteTags(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级列表 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="deleteTags(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column align="center" type="index" label="#"></el-table-column>
        <el-table-column align="center" prop="roleName" label="角色名称"></el-table-column>
        <el-table-column align="center" prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column align="center" label="操作" width="350px">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRoleBtn(scope.row.id)"
            >编辑</el-button>
            <!-- 删除按钮 -->
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRoleBtn(scope.row.id)"
            >删除</el-button>
            <!-- 其他功能按钮 -->
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-share"
              @click="allotRoleBtn(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesDialogVisible"
      width="50%"
      @close="colseAddRoles"
    >
      <el-form :model="addRoleList" :rules="rolesListRules" ref="addRoleRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolesToList">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editRolesDialogVisible"
      width="50%"
      @close="colseEditRoles"
    >
      <el-form :model="editRoleList" :rules="rolesListRules" ref="editRoleRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesToList">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="allotRolesDialogVisible" width="50%" @close="closeallot">
      <!-- 树形图 -->
      <el-tree
        :data="allotList"
        :props="allotProps"
        show-checkbox
        default-expand-all
        :default-checked-keys="allotTreeArray"
        node-key="id"
        ref="allotRef"
      ></el-tree>
      <span slot="footer">
        <el-button @click="allotRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="rightAddAllot">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表数据
      rolesList: [],
      //   添加角色的对话框是否显示
      addRolesDialogVisible: false,
      //   添加用户的数据列表
      addRoleList: {
        roleName: "",
        roleDesc: ""
      },
      //   角色对话框的校验规则
      rolesListRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 1, max: 8, message: "长度在 1 到 8 个字符", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 5, max: 20, message: "长度在 5 到 20 个字符", trigger: "blur" }
        ]
      },
      //   修改对话框的显示与隐藏
      editRolesDialogVisible: false,
      //   修改角色列表数据
      editRoleList: {
        roleName: "",
        roleDesc: ""
      },
      // 分配权限对话框显示与隐藏
      allotRolesDialogVisible: false,
      // 权限列表数据
      allotList: [],
      // 树形图的数据
      allotProps: { label: "authName", children: "children" },
      // 树形图的默认选中数组
      allotTreeArray: [],
      // 分配角色的id
      roleId:''
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 获取角色列表数据
    async getRolesList() {
      const { data } = await this.$http.get("roles");
      // console.log(data);
      this.rolesList = data.data;
    },
    // 添加角色对话框
    addRoles() {
      this.addRolesDialogVisible = true;
    },
    // 关闭添加角色对话框的重置功能
    colseAddRoles() {
      this.$refs.addRoleRef.resetFields();
    },
    // 确定添加用户，发起添加用户接口请求
    addRolesToList() {
      // 预校验
      this.$refs.addRoleRef.validate(async valida => {
        // console.log(valida);
        if (!valida) return;
        const { data } = await this.$http.post("roles", this.addRoleList);
        if (data.meta.status != 201) return this.$message.error(data.meta.msg);
        this.$message.success(data.meta.msg);
        this.addRolesDialogVisible = false;
        this.getRolesList();
        console.log(this.addRoleList);
      });
    },
    // 修改角色对话框
    async editRoleBtn(id) {
      this.editRolesDialogVisible = true;
      const { data } = await this.$http.get("roles/" + id);
      if (data.meta.status != 200) {
        return this.$message.error(data.meta.msg);
      }
      //   console.log(data);

      this.editRoleList = data.data;
      //   console.log(this.editRoleList);
    },
    // 关闭添加角色对话框的重置功能
    colseEditRoles() {
      this.$refs.editRoleRef.resetFields();
    },
    // 修改成功调用接口
    editRolesToList() {
      this.editRolesDialogVisible = false;
      this.$refs.editRoleRef.validate(async valida => {
        if (!valida) return;
        const { data } = await this.$http.put(
          "roles/" + this.editRoleList.roleId,
          {
            roleName: this.editRoleList.roleName,
            roleDesc: this.editRoleList.roleDesc
          }
        );
        this.getRolesList();
      });
    },
    // 删除角色功能
    async deleteRoleBtn(id) {
      const confirm = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      console.log(confirm);

      if (confirm !== "confirm") {
        return this.$message.error(data.meta, msg);
      }
      const { data } = await this.$http.delete("roles/" + id);
      console.log(data);
      this.getRolesList();
      this.$message.success(data.meta.msg);
    },
    // 删除权限
    async deleteTags(role, rightId) {
      const confirm = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      console.log(confirm);
      if (confirm != "confirm") return this.$message.error(data.meta, msg);
      const { data } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      // this.getRolesList()
      // console.log(role);
      role.children = data.data;
    },
    // 分配权限的对话框
    async allotRoleBtn(role) {
      // 在显示对话框之前应该先获取到权限列表的所有数据
      const { data } = await this.$http.get("rights/tree");
      // console.log(data);
      if (data.meta.status != 200) return this.$message.error(data.meta.msg);
      this.allotList = data.data;
      // console.log(this.allotList);
      // this.allotTreeArray=没有children的id
      this.getRecursive(role, this.allotTreeArray);
      this.allotRolesDialogVisible = true;
      // console.log(this.allotTreeArray);
      // 声明一个空数组 存放权限id列表的数组
      // const addRoleArr = [];
      // 角色id
      this.roleId=role.id
    },
    // 利用递归函数让第三级的id值存储到数组中
    getRecursive(node, arr) {
      // node就是父节点
      // 如果节点中没有children属性 就把这个节点的id值传递给数组中
      if (!node.children) return arr.push(node.id);
      // 如果有的话就继续遍历节点 一步一步的将没有children的节点遍历出来
      node.children.forEach(item => {
        this.getRecursive(item, arr);
        // console.log(arr);
      });
    },
    // 关闭权限分配对话框
    closeallot() {
      this.allotTreeArray = [];
    },
    // 确定添加角色权限调用接口
    async rightAddAllot() {
      // 获取权限id列表(所有被选中的子节点和半选节点)
      const addRoleArr = [
        // ...是数组解构 将[1，2，3]===1，2，3
        ...this.$refs.allotRef.getCheckedKeys(),
        ...this.$refs.allotRef.getHalfCheckedKeys()
      ];
      // 将数组转换成用，号拼接的字符串
      const addRoleStr=addRoleArr.join(',')
      // 调用接口
      const {data}=await this.$http.post(`roles/${this.roleId}/rights`,{rids:addRoleStr})
      // console.log(data);
      if(data.meta.status!=200)return this.$message.error(data.meta.msg)
      this.$message.success(data.meta.msg)
      this.getRolesList()
      this.allotRolesDialogVisible=false
      
    }
  }
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 10px;
}
.boderb {
  border-bottom: 1px solid #eee;
}
.boders {
  border-top: 1px solid #eee;
}
.fcenter {
  display: flex;
  align-items: center;
}
</style>